//
//  LinnerControllerViewController.m
//  LINNER
//
//  Created by Kendama on 2017/10/11.
//  Copyright © 2017年 Kendama. All rights reserved.
//

#import "LinnerControlViewController.h"
#import "TabbarView.h"
#import "LinnerSetViewController.h"
#import "DenoiseView.h"
#import "BalancerView.h"
#import "BatteryView.h"

@interface LinnerControlViewController ()<tabbarViewDelegate,DenoiseViewDelegate,BalancerViewDelegate>{
    
    dispatch_source_t timer;
}
@property(nonatomic) uint32_t totalBytesRead;
/** 文字数组 **/
@property(nonatomic,strong) NSArray *titleArray;
/** imageArray **/
@property(nonatomic,strong) NSArray *imageArray;

@property(nonatomic,strong) NSArray *voiceArray;
/** SetheadsetEQ **/
@property(nonatomic,strong) NSArray *headsetEQ;
/** voiceData **/
@property(nonatomic,strong) NSArray *voiceDataArray;

@property(nonatomic,strong) TabbarView *tabbarView;
@property(nonatomic,strong) DenoiseView *denoiseView;
@property(nonatomic,strong) BalancerView *balancerView;
@property(nonatomic,strong) BatteryView *batteryView;

@end

@implementation LinnerControlViewController
- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    // watch for received data from the accessory
    
    _totalBytesRead = 0;
    
    [self setNavigationStyle];
    [self getLinnerStatus];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        [self getBattery];
        
    });
    
}

- (void)viewWillDisappear:(BOOL)animated{
    
    [super viewWillDisappear:animated];
    if(timer){
        dispatch_source_cancel(timer);
        timer = nil;
    }
    NSLog(@"定时器取消");
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.imageArray = @[@"bg_equilibrium",@"bg_bass",@"bg_voice",@"bg_treble"];
    self.titleArray = @[@"均衡模式",@"低音增强",@"人声增强",@"高音增强"];
    self.voiceArray = @[@"关闭",@"风中模式",@"室内模式",@"出行模式",@"监听模式"];
    self.voiceDataArray = @[@"aa01022c00",@"aa01022c03",@"aa01022c04",@"aa01022c01",@"aa01022c02"];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(EQback) name:GetHEADSETEQ object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(headsetVoice) name:GetHEADSETVOICE object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(BATTERY) name:GetHEADSETBATTERY object:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark -- 点击事件
- (void)onRightButtonClick:(id)sender
{
    
    LinnerSetViewController *vc = [LinnerSetViewController new];
    [self.navigationController pushViewController:vc animated:YES];
    
}

#pragma mark -- 事件处理
- (void)getBattery{
    
    /* 开启一个定时器 查询电量*/
    NSLog(@"定时器开启");
    timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_queue_create("1", DISPATCH_QUEUE_CONCURRENT));
    dispatch_source_set_timer(timer, DISPATCH_TIME_NOW, 60 * NSEC_PER_SEC, 5 * NSEC_PER_SEC);
    dispatch_source_set_event_handler(timer, ^{
        
        NSString *sendata = @"aa000302";
        const char *buf = [sendata UTF8String];
        NSMutableData *data = [NSMutableData data];
        if (buf)
        {
            uint32_t len = (uint32_t)strlen(buf);
            
            char singleNumberString[3] = {'\0', '\0', '\0'};
            uint32_t singleNumber = 0;
            for(uint32_t i = 0 ; i < len; i+=2)
            {
                if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
                {
                    singleNumberString[0] = buf[i];
                    singleNumberString[1] = buf[i + 1];
                    sscanf(singleNumberString, "%x", &singleNumber);
                    uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                    [data appendBytes:(void *)(&tmp) length:1];
                }
                else
                {
                    break;
                }
            }
            
            NSLog(@"发送%@",data);
            [[EADSessionController sharedController] writeData:data];
        }
        
        
    });
    dispatch_resume(timer);
    
    
}

/** 电池电量  **/
- (void)BATTERY{
    
    NSLog(@"%.1f",20*((double)[AppDelegate globalDelegate].GetheadsetBattery/100));
    
    [self.batteryView setBatteryValue:(double)[AppDelegate globalDelegate].GetheadsetBattery/100];

//    self.batteryValue.text = [NSString stringWithFormat:@"%.f%%",(double)[AppDelegate globalDelegate].GetheadsetBattery];
//    
//    self.batteryNSLayout.constant = 20-20*((double)[AppDelegate globalDelegate].GetheadsetBattery/100) + 4;
    
}

/** 获取耳机模式 **/
- (void)EQback{
    
    [self.balancerView setBalancerViewSelected:[AppDelegate globalDelegate].GetheadsetEQ];
    
}

/** 获得耳机降噪/监听状态 **/
- (void)headsetVoice{
    
//    [self.voiceBtn setTitle:MyNSLocalizedString(self.voiceArray[[AppDelegate globalDelegate].GetheadsetVoice]) forState:UIControlStateNormal];
    
    [self.denoiseView setDenoiseViewSelected:[AppDelegate globalDelegate].GetheadsetVoice];
    NSLog(@"%@",self.voiceArray[[AppDelegate globalDelegate].GetheadsetVoice]);
}

- (void)getLinnerStatus{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.2 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        /*获得耳机降噪／监听状态*/
        NSString *sendata = @"aa0002ac";
        const char *buf = [sendata UTF8String];
        [self sendata:buf];
    });

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.6 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        /*获取耳机eq状态*/
        NSString *sendata = @"aa000294";
        const char *buf = [sendata UTF8String];
        [self sendata:buf];
        
    });
    
}

- (void)sendata:(const char*)buf{
    
    NSMutableData *data = [NSMutableData data];
    if (buf)
    {
        uint32_t len = (uint32_t)strlen(buf);
        
        char singleNumberString[3] = {'\0', '\0', '\0'};
        uint32_t singleNumber = 0;
        for(uint32_t i = 0 ; i < len; i+=2)
        {
            if ( ((i+1) < len) && isxdigit(buf[i]) && (isxdigit(buf[i+1])) )
            {
                singleNumberString[0] = buf[i];
                singleNumberString[1] = buf[i + 1];
                sscanf(singleNumberString, "%x", &singleNumber);
                uint8_t tmp = (uint8_t)(singleNumber & 0x000000FF);
                [data appendBytes:(void *)(&tmp) length:1];
            }
            else
            {
                break;
            }
        }
        NSLog(@"综合发送%@",data);
        
        [[EADSessionController sharedController] writeData:data];
    }
    
}

#pragma mark -- 代理 
- (void)tabbarSelected:(NSInteger)index
{
    switch (index) {
        case 0:
        {
            [self.view bringSubviewToFront:self.denoiseView];
        }
            break;
        case 1:
        {
            [self.view bringSubviewToFront:self.balancerView];
        }
            break;
        case 2:
        {
            [self.view bringSubviewToFront:self.batteryView];
        }
            break;
        default:
            break;
    }
}

- (void)denoiseViewSelected:(NSInteger)index
{
    NSString *senddata = self.voiceDataArray[index];
    const char *buf = [senddata UTF8String];
    [self sendata:buf];
}

- (void)balancerViewSelected:(NSInteger)index
{
    const char *buf = [self.headsetEQ[index] UTF8String];
    [self sendata:buf];
    
}

#pragma mark -- 懒加载
- (TabbarView *)tabbarView
{
    if(!_tabbarView)
    {
        UIView *superView = self.view;
        _tabbarView = [[TabbarView alloc]init];
        [superView addSubview:_tabbarView];
        _tabbarView.delegate = self;
    }
    return _tabbarView;
}

- (DenoiseView *)denoiseView
{
    if(!_denoiseView)
    {
        UIView *superView = self.view;
        _denoiseView = [[DenoiseView alloc]init];
        [superView addSubview:_denoiseView];
        _denoiseView.delegate = self;
    }
    return _denoiseView;
}

- (BalancerView *)balancerView
{
    if(!_balancerView)
    {
        UIView *superView = self.view;
        _balancerView = [[BalancerView alloc]init];
        [superView addSubview:_balancerView];
        _balancerView.delegate = self;
    }
    return _balancerView;
}

- (BatteryView *)batteryView
{
    if(!_batteryView)
    {
        UIView *superView = self.view;
        _batteryView = [[BatteryView alloc]init];
        [superView addSubview:_batteryView];
    }
    return _batteryView;
}

- (NSArray *)headsetEQ{
    
    if (!_headsetEQ) {
        
        _headsetEQ = @[@"aa01021400",@"aa01021401",@"aa01021402",@"aa01021403"];
    }
    return _headsetEQ;
}


- (void)masLayoutSubview
{
    __weak UIView *superView = self.view;
    
    [self.tabbarView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.mas_equalTo(superView.mas_bottom);
        make.left.right.mas_equalTo(superView);
        make.height.mas_equalTo(px1920Height(150));
    }];
    
    
    [self.balancerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.mas_equalTo(superView);
        make.bottom.mas_equalTo(self.tabbarView.mas_top);
    }];
    
    [self.batteryView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.mas_equalTo(superView);
        make.bottom.mas_equalTo(self.tabbarView.mas_top);
    }];
    
    [self.denoiseView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(superView.mas_top).with.offset(64);
        make.left.right.mas_equalTo(superView);
        make.bottom.mas_equalTo(self.tabbarView.mas_top);
    }];
    
}

- (void)setNavigationStyle{
    
    [self setNavigationBarTitle:MyNSLocalizedString(@"NC50 Pro")];
    [self setLeftButtonImage:[UIImage imageNamed:@"tittle_back_nor"]];
    [self.navigationController.navigationBar makeTransparent_nornav];
    [self setRightButtonImage:[UIImage imageNamed:@"icon_set"]];
    
}


@end
